<template>
  <div class="page-container">
    <el-card class="card-container">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="城市名称">
          <el-input v-model="queryParams.cityName" placeholder="输入城市名称搜索" clearable
                    @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="所属省份">
          <el-input v-model="queryParams.province" placeholder="输入省份搜索" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button type="success" :icon="Plus" @click="handleAdd">新增城市</el-button>
        </el-form-item>
      </el-form>

      <div class="table-container">
        <el-table
            :data="tableData"
            v-loading="loading"
            border
            style="width: 100%"
            :header-cell-style="{background:'#f5f7fa', fontWeight: 'bold'}">
          <el-table-column type="index" label="序号" width="80" align="center" :index="calculateIndex" />
          <el-table-column prop="cityCode" label="城市编码" width="120" />
          <el-table-column prop="cityName" label="城市名称" min-width="150" />
          <el-table-column prop="province" label="所属省份" min-width="150" />
          <el-table-column prop="pharmaCompanyCount" label="医药公司数" width="150" align="center">
            <template #default="{ row }">
              <el-tag :type="row.pharmaCompanyCount > 30 ? 'success' : 'info'">
                {{ row.pharmaCompanyCount }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="salesSiteCount" label="销售点数量" width="150" align="center" />
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="fetchData"
          @current-change="fetchData"
          class="pagination" />

      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" @close="resetForm">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
          <el-form-item label="城市编码" prop="cityCode">
            <el-input v-model="form.cityCode" placeholder="请输入城市编码" />
          </el-form-item>
          <el-form-item label="城市名称" prop="cityName">
            <el-input v-model="form.cityName" placeholder="请输入城市名称" />
          </el-form-item>
          <el-form-item label="所属省份" prop="province">
            <el-input v-model="form.province" placeholder="请输入所属省份" />
          </el-form-item>
          <el-form-item label="医药公司数" prop="pharmaCompanyCount">
            <el-input-number v-model="form.pharmaCompanyCount" :min="0" controls-position="right" />
          </el-form-item>
          <el-form-item label="销售点数量" prop="salesSiteCount">
            <el-input-number v-model="form.salesSiteCount" :min="0" controls-position="right" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import cityApi from '../../../api/city'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Search, Plus, Edit, Delete} from '@element-plus/icons-vue'

// --- 响应式状态定义 ---
const tableData = ref([])
const loading = ref(false)

// 查询参数
const queryParams = reactive({
  cityName: '',
  province: ''
})

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 表单引用
const formRef = ref(null)

// 表单数据模型
const initialFormState = {
  id: null,
  cityCode: '',
  cityName: '',
  province: '',
  pharmaCompanyCount: 0,
  salesSiteCount: 0
}
const form = reactive({...initialFormState})

// 表单校验规则
const rules = {
  cityCode: [
    {required: true, message: '请输入城市编码', trigger: 'blur'},
    {pattern: /^\d{6}$/, message: '城市编码必须为6位数字', trigger: 'blur'}
  ],
  cityName: [
    {required: true, message: '请输入城市名称', trigger: 'blur'}
  ],
  province: [
    {required: true, message: '请输入所属省份', trigger: 'blur'}
  ]
}

// 核心方法
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      cityName: queryParams.cityName || null,
      province: queryParams.province || null
    }
    const data = await cityApi.getCityPage(params)
    tableData.value = data.records
    pagination.total = data.total
  } catch (error) {
    console.error("获取城市列表失败:", error)
  } finally {
    loading.value = false
  }
}

const calculateIndex = (index) => {
  const currentPage = pagination.pageNum;
  const pageSize = pagination.pageSize;
  return (currentPage - 1) * pageSize + index + 1;
}

const handleSearch = () => {
  pagination.pageNum = 1
  fetchData()
}

const resetForm = () => {
  Object.assign(form, initialFormState);
  formRef.value?.clearValidate();
}

const handleAdd = () => {
  resetForm();
  dialogTitle.value = '新增城市';
  dialogVisible.value = true;
}

const handleEdit = (row) => {
  resetForm();
  Object.assign(form, row);
  dialogTitle.value = '编辑城市';
  dialogVisible.value = true;
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个城市吗？', '警告', {type: 'warning'})
    await cityApi.deleteCity(id);
    ElMessage.success('删除成功');
    fetchData();
  } catch (error) {
    if (error !== 'cancel') {
      console.error("删除城市失败:", error);
    }
  }
}

const submitForm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    if (form.id) {
      await cityApi.updateCity(form);
      ElMessage.success('修改成功');
    } else {
      await cityApi.addCity(form);
      ElMessage.success('新增成功');
    }
    dialogVisible.value = false;
    fetchData();
  } catch (validationError) {
    console.log('表单校验失败:', validationError);
  }
}

onMounted(() => {
  fetchData();
})
</script>

<style scoped>
.page-container {
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.card-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.search-form {
  margin-bottom: 20px;
}

.table-container {
  flex: 1;
  overflow: auto;
  margin-bottom: 20px;
}

.el-table {
  width: 100%;
}

.el-table__body {
  width: 100% !important;
}

.el-table th, .el-table td {
  padding: 12px 0;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.el-select {
  width: 100%;
}
</style>